package com.beyond.flow.container

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.beyond.flow.inter.UiEvent
import com.beyond.flow.inter.UiState
import kotlinx.coroutines.CoroutineScope

/**
 * @author chenshiyang
 * @time 2022/11/11 09:27
 * @name beyond-kotlin-frame
 * @class describe
 */
/**
 * 构建viewModel的Ui容器，存储Ui状态和一次性事件
 * kotlin 扩展方法
 */
fun <STATE : UiState, SINGLE_EVENT : UiEvent> ViewModel.containers(
    initialState: STATE,
): Lazy<MutableContainer<STATE, SINGLE_EVENT>> {
    return ContainerLazy(initialState, viewModelScope)
}

/**
 * 委托模式
 */
class ContainerLazy<S : UiState, E : UiEvent>(state: S, scope: CoroutineScope) :
    Lazy<MutableContainer<S, E>> {
    private var cached: MutableContainer<S, E>? = null

    override val value: MutableContainer<S, E> =
        cached ?: RealContainer<S, E>(state, scope).also { cached = it }

    override fun isInitialized() = cached != null
}